import re
from lxml import etree
import requests
from retrying import retry
from Logs.log import log1
from db_sql import insert_db
from utils import exchange_rate_url as url, headers, exr
from datetime import datetime


@retry(stop_max_attempt_number=3)
def request():
    resp = requests.get(url, headers=headers)
    html = etree.HTML(resp.content.decode())
    return html


def parse(html):
    db_dict = {}
    main_label = html.xpath("//table[@class='genTbl closedTbl historicalTbl']/tbody/tr[1]")[0]
    price_date = main_label.xpath("./td[1]/text()")[0].strip()  # 2019年11月12日
    date_str = re.search(r"(\d+)\D+(\d+)\D+(\d+)", price_date)
    db_dict["price_date"] = date_str.group(1) + "/" + date_str.group(2) + "/" + date_str.group(3)
    db_dict["id"] = date_str.group(1) + date_str.group(2) + date_str.group(3) + exr
    db_dict["avg_price"] = html.xpath("//span[@id='fl_header_pair_lst']/text()")[0].strip()
    db_dict["change_amount"] = html.xpath("//span[@id='fl_header_pair_chg']/text()")[0].strip()
    db_dict["change_range"] = html.xpath("//span[@id='fl_header_pair_pch']/text()")[0].strip()
    unit = html.xpath("//h1[@class='float_lang_base_1 relativeAttr']/text()")[0].strip()
    db_dict["unit"] = unit.split(" - ")[0].replace(" ", "")
    return db_dict


def save(db_dict):
    db_dict["raw_name"] = "美元/人民币汇率"
    db_dict["raw_type"] = exr
    db_dict["source"] = "英为财情"
    db_dict["lower_price"] = ""
    db_dict["higher_price"] = ""
    db_dict["create_time"] = datetime.now().strftime('%Y/%m/%d %H:%M:%S')
    insert_db(db_dict)


def run():
    try:
        html = request()
        db_dict = parse(html)
        save(db_dict)
    except Exception as e:
        log1.error(e)
    log1.info("汇率END!")


if __name__ == '__main__':
    run()